const { login } = require('../controller/user');
const { SuccessModel, ErrorModel } = require('../model/responseModel');
const { getCookieExpires, checkLogin } = require('../common/utils');
const { setRedis, getRedis } = require('../db/redis');

const handleUserRouter = (req, res) => {
    const method = req.method;
    const cookie = req.cookie;
    const path = req.path;
    const query = req.query;
    const body = req.body;

    if (method === 'GET' && path === '/api/user/login') {
        return login(query.username, query.password).then(userData => {
            const token = cookie.token || `token_${Date.now()}`;
            if (userData) {
                setRedis(token, userData);
                // 找的到 userData 设置相关 token_id 的 cookie
                res.setHeader('set-cookie', `token=${token}; path=/; httpOnly; expires=${getCookieExpires(1)}`);
                return new SuccessModel('登录成功');
            }
            // 找不到 userData 就删除相关 token_id 的 cookie
            res.setHeader('set-cookie', `token=${token}; path=/; httpOnly; expires=${new Date(0)}`);
            return new ErrorModel('登录失败');
        });
    }

    if (method === 'GET' && path === '/api/user/login-test') {
        const token = cookie.token || '';
        if (token) {
            return checkLogin(req).then(loginStatus => {
                if (loginStatus) {
                    return Promise.resolve(new SuccessModel('已经登录'));
                } else {
                    return Promise.resolve(new ErrorModel('尚未登录'));
                }
            });
        }
        return Promise.resolve(new ErrorModel('尚未登录'));
    }
};

module.exports = handleUserRouter;
